package com.example.a2209_shop.fg

import android.app.Activity
import android.content.Intent
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.viewpager2.widget.ViewPager2
import com.alibaba.android.arouter.launcher.ARouter
import com.blankj.utilcode.util.SPUtils
import com.blankj.utilcode.util.ToastUtils
import com.bumptech.glide.Glide
import com.example.a2209_shop.R
import com.example.a2209_shop.adapter.MyFragAdapter
import com.example.a2209_shop.database.DataBaseUtils
import com.example.a2209_shop.databinding.FragmentMineBinding
import com.example.a2209_shop.fgViewModel.MineViewModel
import com.example.a2209_shop.utils.MyTabEntity
import com.example.base.entity.UserEntity
import com.example.base.mvvm.BaseFragment
import com.example.base.mvvm.BaseViewFragment
import com.flyco.tablayout.listener.CustomTabEntity
import com.flyco.tablayout.listener.OnTabSelectListener
import com.github.gzuliyujiang.wheelpicker.AddressPicker
import com.github.gzuliyujiang.wheelpicker.DatePicker
import com.github.gzuliyujiang.wheelpicker.OptionPicker
import com.github.gzuliyujiang.wheelpicker.annotation.AddressMode
import com.github.gzuliyujiang.wheelpicker.entity.DateEntity
import com.wildma.pictureselector.PictureBean
import com.wildma.pictureselector.PictureSelector
import okhttp3.MediaType
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.MultipartBody
import okhttp3.RequestBody
import java.io.File


class MineFragment : BaseFragment<FragmentMineBinding, MineViewModel>() {
    val list = mutableListOf<Fragment>()
    val tabs = ArrayList<CustomTabEntity>()
    lateinit var myFragAdapter: MyFragAdapter
    lateinit var user:UserEntity//延迟初始化用户实体类
    override fun initData() {
       user = DataBaseUtils.getDb().getUserDao().queryBy(SPUtils.getInstance().getInt("id"))!!
        //回显用户信息
        context?.let { Glide.with(it).load(user.icon).into(binding.userIcon) }
        binding.userName.text = user.username

        //点击退出登录
        binding.logout.setOnClickListener {
            SPUtils.getInstance().clear()//清空保存内容处于未登录状态
            ARouter.getInstance().build("/app/LoginActivity").navigation()
        }
        //点击用户其他信息 --弹出不同样式的框

        binding.userOther.setOnClickListener {
            //弹出选项框
            /*val list = mutableListOf<String>()//存放性别
            list.add("男")
            list.add("女")
            list.add("保密")
            val optionPicker = OptionPicker(requireActivity())
            optionPicker.setTitle("请选择性别")
            optionPicker.setData(list)
            optionPicker.setOnOptionPickedListener { position, item ->
                binding.userOther.text = list[position]
            }
            optionPicker.show()*/
            //弹出地址框
           /* val addressPicker = AddressPicker(requireActivity())
            addressPicker.setTitle("请选择配送地址")
            addressPicker.setAddressMode(AddressMode.PROVINCE_CITY_COUNTY)
            addressPicker.setOnAddressPickedListener { province, city, county ->
                binding.userOther.text = "${province.name}${city.name}${county.name}"
            }
            addressPicker.show()*/
            //日期弹出框
            val datePicker = DatePicker(requireActivity())
            datePicker.setTitle("请选择配送日期")
            datePicker.wheelLayout.setRange(DateEntity.target(1900,1,1), DateEntity.today(),DateEntity.today())
            datePicker.setOnDatePickedListener { year, month, day ->
                binding.userOther.text = "$year-$month-$day"
            }
            datePicker.show()
        }

        //点击图片实现变更头像
        binding.userIcon.setOnClickListener {
            PictureSelector.create(this,300).selectPicture()
        }

        viewModel.updateIconSuccess.observe(this){
            ToastUtils.showLong(it.message)
        }


    }

    override fun initView() {
        list.add(GkFragment())
        list.add(ScFragment())
        list.add(PayingFragment())
        list.add(PayedFragment())
        tabs.add(MyTabEntity("观看过"))
        tabs.add(MyTabEntity("收藏"))
        tabs.add(MyTabEntity("待支付"))
        tabs.add(MyTabEntity("已支付"))

        myFragAdapter = MyFragAdapter(requireActivity(),list)
        binding.vp.adapter = myFragAdapter

        binding.ctl.setTabData(tabs)
        //viewpager滑动  tab变化
        binding.vp.registerOnPageChangeCallback(object :ViewPager2.OnPageChangeCallback(){
            override fun onPageSelected(position: Int) {
                binding.ctl.currentTab = position
                super.onPageSelected(position)
            }
        })

        binding.ctl.setOnTabSelectListener(object :OnTabSelectListener{
            override fun onTabSelect(position: Int) {
                binding.vp.setCurrentItem(position)
            }

            override fun onTabReselect(position: Int) {
            }
        })



    }

    override fun getViewModel(): Class<MineViewModel>  = MineViewModel::class.java

    override fun getLayout(): Int  = R.layout.fragment_mine


    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if(requestCode==300&&resultCode==Activity.RESULT_OK){
            val pictureBean = data?.extras?.get(PictureSelector.PICTURE_RESULT) as PictureBean
            context?.let { Glide.with(it).load(pictureBean.path).into(binding.userIcon) }

            val body = RequestBody.create("multipart/form-data".toMediaTypeOrNull(), File(pictureBean.path))
            val part = MultipartBody.Part.createFormData("file","a.jpg",body)
            viewModel.updateIcon(part)

        }
    }

}